package com.hm.homepage.controller;

import com.hm.homepage.entity.Website;
import com.hm.homepage.service.WebsiteService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.List;

@Controller
public class WebsiteController {

    @Autowired
    private WebsiteService websiteService;
    
    @Value("${page.title}")
    private String pageTitle;

    @GetMapping("/")
    public String index(Model model) {
        List<Website> websites = websiteService.getAllWebsites();
        List<String> categories = websiteService.getAllCategories();
        
        model.addAttribute("websites", websites);
        model.addAttribute("categories", categories);
        model.addAttribute("activeCategory", "all");
        model.addAttribute("pageTitle", pageTitle);
        return "index";
    }

    @GetMapping("/category/{category}")
    public String websitesByCategory(@PathVariable String category, Model model) {
        List<Website> websites = websiteService.getWebsitesByCategory(category);
        List<String> categories = websiteService.getAllCategories();
        
        model.addAttribute("websites", websites);
        model.addAttribute("categories", categories);
        model.addAttribute("activeCategory", category);
        model.addAttribute("pageTitle", pageTitle);
        return "index";
    }

    @GetMapping("/websites")
    @ResponseBody
    public List<Website> getAllWebsites() {
        return websiteService.getAllWebsites();
    }

    @PostMapping("/websites")
    @ResponseBody
    public Website saveWebsite(@RequestBody Website website) {
        website.setCreatedAt(LocalDateTime.now());
        websiteService.save(website);
        return website;
    }
    
    @PutMapping("/websites/{id}")
    @ResponseBody
    public Website updateWebsite(@PathVariable Long id, @RequestBody Website website) {
        website.setId(id);
        websiteService.updateById(website);
        return website;
    }

    @DeleteMapping("/websites/{id}")
    @ResponseBody
    public void deleteWebsite(@PathVariable Long id) {
        websiteService.removeById(id);
    }
    
    @GetMapping("/websites/{id}")
    @ResponseBody
    public Website getWebsite(@PathVariable Long id) {
        return websiteService.getById(id);
    }
}